package com.flink.demo.watermark08;

import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.TimeCharacteristic;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.AssignerWithPeriodicWatermarks;
import org.apache.flink.streaming.api.watermark.Watermark;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;

import javax.annotation.Nullable;

/**
 * 模拟一个实时接收 Socket 的 DataStream 程序，
 * 代码中使用 AssignerWithPeriodicWatermarks 来设置水印，
 * 将接收到的数据进行转换，分组并且在一个 5秒的窗口内获取该窗口中第二个元素最小的那条数据。
 * <p>
 * 测试数据：
 * flink,1588659181000
 * flink,1588659182000
 * flink,1588659183000
 * flink,1588659184000
 * flink,1588659185000
 * <p>
 * 乱序数据：
 * flink,1588659181000
 * flink,1588659182000
 * flink,1588659183000
 * flink,1588659184000
 * flink,1588659185000
 * flink,1588659180000
 * flink,1588659186000
 * flink,1588659187000
 * flink,1588659188000
 * flink,1588659189000
 * flink,1588659190000
 *
 * @author zsyoung@qq.com
 * 2020/7/19 11:31
 */
public class watermark {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        //设置为eventtime事件类型
        env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime);
        //设置水印生成时间间隔100ms
        env.getConfig().setAutoWatermarkInterval(100);

        DataStream<String> dataStream = env
                .socketTextStream("127.0.0.1", 9000)
                .assignTimestampsAndWatermarks(new AssignerWithPeriodicWatermarks<String>() {

                    private Long currentTimestamp = 0L;
                    //设置允许乱序的时间
                    private Long maxOutOfOrderness = 5000L;

                    @Nullable
                    @Override
                    public Watermark getCurrentWatermark() {
                        return new Watermark(currentTimestamp - maxOutOfOrderness);
                    }

                    @Override
                    public long extractTimestamp(String s, long l) {
                        String[] arr = s.split(",");
                        long timeStamp = Long.parseLong(arr[1]);
                        currentTimestamp = Math.max(timeStamp, currentTimestamp);
                        System.err.println(s + ",EventTime:" + timeStamp + ",watermark:" + (currentTimestamp - maxOutOfOrderness));
                        return timeStamp;
                    }
                });

        dataStream.map(new MapFunction<String, Tuple2<String, Long>>() {
            @Override
            public Tuple2<String, Long> map(String s) throws Exception {
                String[] split = s.split(",");
                return new Tuple2<String, Long>(split[0], Long.parseLong(split[1]));
            }
        })
                .keyBy(0)
                .window(TumblingEventTimeWindows.of(Time.seconds(5)))
                .minBy(1)
                .print();

        env.execute("WaterMark Test Demo");
    }
}
